package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.impl.DishServiceImpl;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
@Slf4j
public class DishController {
    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    public Result addNewDish(@RequestBody DishDTO dishDTO){
        dishService.addNewDish(dishDTO);
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }

    /**
     * 分页查询全部菜品
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult> getAllDish(DishPageQueryDTO dishPageQueryDTO){
         return Result.success(dishService.getAllDish(dishPageQueryDTO));
    }

    /**
     * 设置菜品状态
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<Object> setDishStatus(@RequestParam Long id, @PathVariable Integer status){
        log.info("status");
        dishService.setDishStatus(id,status);
        Set keys= redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 查询菜品 by ID
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishVO> getDishById (@PathVariable Long id){
        return Result.success(dishService.getDishById(id));
    }

    /**
     * 更新菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public Result<Object> updateDish(@RequestBody DishDTO dishDTO){
        dishService.updateDish(dishDTO);
        Set keys= redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 删除菜品 （可批量删除）
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<Object> deleteDishs(@RequestParam List<Integer> ids){
        dishService.deleteDishs(ids);
        Set keys= redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    /**
     * 查询菜品 by type
     */
    @GetMapping("/list")
    public Result<List<Dish>> getDishsByType(@RequestParam Long categoryId){
        return Result.success(dishService.getDishsByType(categoryId));
    }
}
